#include <dataitem.h>
using namespace libxcom;

int main(int argc, const char *argv[]) {
    // setenv("LOG", "stdout", 1);

    const std::string templ = "#modbus协议\n"
                              "def crc16: $crc($1,0x8005,0xffff,0x0000,0)\n"
                              "# $addr $len 都是输入的参数\n"
                              "def send:     [$addr 03H $1  $itom(2,$len) $crc16($group(0,$pos))]\n"
                              "def recv:     [$addr 03H     $ditch(1,$assign(&dl,$0))     $data($ditch($dl))  "
                              "$ditch(2,$chk($0,$crc16($group(0,$pos))))]";
    libxcom::DataItem ditem("测试协议", templ, "$int($data)", 1);
    ditem.SetVar("addr", (uint8_t)0x51);
    ditem.SetVar("len", 2);
    ditem.EmptyParam();
    ditem.PushParam((uint8_t)0x04);

    // 指令序列化, 绑定send函数
    OpValue cmd = ditem.GenerateCmd("send");
    cmd.Show();
    if (cmd.IsEmpty())
        return -1;
    CmdValue genCmd = cmd.GenCmd();
    genCmd.Show();

    // 处理接收指令， 这里假设
    OpValue result;
    uint8_t cmd_buf[] = {0x51,0x03,0x04,0x00,0x00,0x00,0x1E,0x2A,0x3E};
    CmdValue recv(cmd_buf, sizeof(cmd_buf)/sizeof(cmd_buf[0]));
    recv.Show();
    // 反序列化， 绑定recv函数
    if (ditem.ParseRecvCmd(recv, "recv") != RECV_COMPLETE) {
        return -1;
    }
    result = ditem.Result();
    result.Show();
    if (result != 0x1E) {
        HTELINK_LOG_ERR("not match: %02x", result.Integer());
        return -1;
    }
    return 0;
}
